package com.wustl.android.hood;

import java.io.IOException;

import com.facebook.api.FacebookException;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;

public class FaceBookMain extends Activity{
	private static final int FB_LOGIN_ACTIVITY_RESULT = 0;
	private volatile boolean logged_in = false;
	@Override
	protected void onActivityResult(int requestCode, int resultCode, String data, Bundle extra) {
		if (resultCode == FB_LOGIN_ACTIVITY_RESULT) {
			logged_in = true;
		}
	}
	
	private class FBLoginChromeClient extends WebChromeClient {
		private com.facebook.api.FacebookJsonRestClient fb;
		private com.google.android.maps.Point loc;
		private String auth;
		public FBLoginChromeClient(com.facebook.api.FacebookJsonRestClient fb, com.google.android.maps.Point loc, String auth) {
			this.fb = fb;
			this.loc = loc;
			this.auth = auth;
		}
		
		// TODO: replace this crude state machine
		// implementation by a more sophisticated
		// one that is more likely to be
		// consistent with the rest of the world.
		// For example, we could scrape web pages
		// to distinguish successful from
		// unsuccessful logins...
		// step 0: initial
		// step 1: login form loaded
		// step 2: login response loaded
		// step 3: done
		public volatile int step = 0;
	
		@Override
		public void onProgressChanged(WebView view, int newProgress) {
			super.onProgressChanged(view, newProgress);
			if (newProgress != 100) return;
			if (step < 3) ++step;
			if (step == 2) {
				view.loadUrl("http://code.google.com/p/hood/");
			}
			if (step == 3 && view.getUrl().startsWith("http://code.google.com/")) {
				try {
					try {
						fb.auth_getSession(auth);
					}
					catch (FacebookException e) {
						//TODO: improve robustness
						throw new RuntimeException("This is a bug in hood.");
					}
					if (false) fb.users_setStatus(loc.toString());
				}
				catch (FacebookException e) {
					if (e.getCode() == 250) {
						// get user to visit
						//  http://www.facebook.com/authorize.php?api_key=OUR_KEY&ext_perm=status_update&v=1.0				
					}
					else {
						throw new RuntimeException("This was unexpected.", e);
					}
				}
				catch (IOException e) {
					throw new RuntimeException("This was unexpected.", e);
				}
			}
		}
	}
	
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        setContentView(R.layout.facebook);
        DbLocations dbl = new DbLocations(this);
        com.google.android.maps.Point loc = null;
        try {
        	dbl.open();
            Cursor locRow = 
                dbl.fetchLocation(getIntent().getLongExtra("mapLocationId", -1));
            loc =
				new com.google.android.maps.Point(
					(int)(1E6 * locRow.getDouble(locRow.getColumnIndex(DbLocations.KEY_LATITUDE))),
					(int)(1E6 * locRow.getDouble(locRow.getColumnIndex(DbLocations.KEY_LONGITUDE))));
        }
        finally {
        	dbl.close();
        }
        String fbAPIKey = "a591201f44aae5338a05975e5178b218";
		String fbAPISecret = "ff9d1ad3108252bb7dd3afb4cbcce5dd";
		com.facebook.api.FacebookJsonRestClient fb =
			new com.facebook.api.FacebookJsonRestClient(
				fbAPIKey,
				fbAPISecret);
		try {
			fb.setIsDesktop(true);
			// get user to login to FB
			String auth = fb.auth_createToken();
			WebView login = (WebView)findViewById(R.id.fblogin);
			WebViewClient loginViewClient = new WebViewClient();
			loginViewClient.shouldOverrideUrlLoading(login, "http://facebook.com");
			login.setWebViewClient(loginViewClient);
			FBLoginChromeClient loginChromeClient = new FBLoginChromeClient(fb, loc, auth);
			login.setWebChromeClient(loginChromeClient);
			login.loadUrl(
					String.format(
							"https://www.facebook.com/login.php?api_key=%1$s&v=1.0&auth_token=%2$s&popup",
							fbAPIKey,
							auth));
//			Intent login = new Intent();
//			android.content.ComponentName browser = new android.content.ComponentName("com.google.android.browser", "com.google.android.browser.BrowserActivity");
//			login.setComponent(browser);
//			login.setAction(Intent.VIEW_ACTION);
//			login.addCategory(Intent.BROWSABLE_CATEGORY);
//			login.setData(
//					Uri.parse(
//						String.format(
//							"https://www.facebook.com/login.php?api_key=%1$s&v=1.0&auth_token=%2$s&popup",
//							fbAPIKey,
//							auth)));
//			startSubActivity(login, FB_LOGIN_ACTIVITY_RESULT);
//			long startTime = System.currentTimeMillis();
//			long endByTime = startTime + 100000;
//			while (!logged_in) {
//				try {
//					Thread.sleep(1L);
//				} catch (InterruptedException e) {
//					// ignore
//				}
//				if (System.currentTimeMillis() > endByTime) break;
//			}
//			
		} catch (FacebookException e) {
			if (e.getCode() == 250) {
				// get user to visit
				//  http://www.facebook.com/authorize.php?api_key=OUR_KEY&ext_perm=status_update&v=1.0				
			}
			else {
				throw new RuntimeException("This was unexpected.", e);
			}
		} catch (IOException e) {
			throw new RuntimeException("This was unexpected.", e);
		}
    }
    
}
